package com.iformacion;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class AccesoDBS {
	
	private DataSource ds = null;
	
	//SINGLETON
	private static AccesoDBS instance = null;
	
	private AccesoDBS() throws SQLException {
		//Creo un contexto, y si no puedo lanzo una Exception
		Context ctx = null;
		try {
			ctx = new InitialContext();
		} catch(NamingException e) {
			e.printStackTrace();
		}
		if(ctx == null) {
			throw new SQLException("No hay contexto");
		}
		
		//Intento recuperar el DataSource
		try {
			this.ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysqlDS");
		} catch(NamingException e) {
			e.printStackTrace();
		}
		if(this.ds == null) {
			throw new SQLException("No hay un datasource");
		}
	}
	
	public static AccesoDBS getInstance() {
		if(instance == null) {
			try {
				instance = new AccesoDBS();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return instance;
	}
	
	public Connection getConnection() throws SQLException {
		return this.ds.getConnection();
	}
}
